import React from 'react';
import { Card, Button, Table, Space, Modal, TableProps, message, Cascader } from 'antd';
import { useParams } from 'react-router-dom';
import _ from 'lodash';
import { type FormPanelObject, InputType } from 'lfun-bg-comp';
import utils from '@/utils';
import FormPanelWrapper from '../../component/FormPanelWrapper';
import { TeaResearchAchievementsSrv } from '@/service/teacher';
import {
  RESEARCH_LEVEL,
  RESEARCH_MODE,
  RESEARCH_OTHER_LEVEL,
  RESEARCH_ROLE,
  RESEARCH_ROLE_RANK,
  RESEARCH_TYPE,
  PROJECT_SOURCE,
  BOOK_TYPE,
  RESEARCH_REWARD_TYPE,
  ARTWORK_TYPE,
  PATENT_TYPE,
  PAPER_ROLE,
  ARTWORK_ROLE,
  PATENT_ROLE,
  COMPETITION_ROLE,
  PROJECT_ROLE,
  INDEXING_STATUS,
  PERSONAL_RANK,
} from '@/constant/teachOptions';
import { YES_NO } from '@/constant/basicOptions';
import { countries } from '@/constant/country';
import { isPermissionOperate } from '@/component/permission-button';

const Groups: React.FC<{ achievement_type?: string; isEditPanel?: boolean }> = ({
  achievement_type = '1',
  isEditPanel = true,
}) => {
  const columns: TableProps['columns'] = [
    {
      title: '科研成果种类',
      dataIndex: 'research_achievement_type',
      key: 'research_achievement_type',
      render: (text: any) => {
        return _.find(RESEARCH_TYPE, { value: String(text) })?.label;
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (text: any) => {
        return _.find(RESEARCH_MODE, { value: String(text) })?.label;
      },
    },
    {
      title: '是否是代表性成果或项目',
      dataIndex: 'representative_or_project',
      key: 'representative_or_project',
      render: (text: any) => {
        return _.find(YES_NO, { value: Boolean(text) })?.label;
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '学科领域',
      dataIndex: 'disciplinary_field',
      key: 'disciplinary_field',
    },
    {
      title: '本人角色',
      dataIndex: 'role',
      key: 'role',
      render: (text: any) => {
        return _.find(RESEARCH_ROLE, { value: String(text) })?.label;
      },
    },
    {
      title: '操作',
      key: 'actions',
      //width: 200,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          {isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          )}
          {isEditPanel && (
            <Button type="link" onClick={() => handleDelete(record)}>
              删除
            </Button>
          )}
          {!isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              查看
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const list = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      span: 12,
      inputs: [
        {
          label: '科研成果种类',
          name: 'research_achievement_type',
          key: 'research_achievement_type',
          required: true,
          disabled: true,
          inputType: InputType.select,
          renderOption: RESEARCH_TYPE,
        },
        {
          label: '类型',
          name: 'type',
          key: 'type',
          inputType: InputType.children,
          children: <Cascader />,
          renderOption: (form: FormPanelObject) => {
            const research_achievement_type = form.getFieldValue('research_achievement_type');
            const options = {
              1: RESEARCH_MODE,
              2: BOOK_TYPE,
              4: RESEARCH_REWARD_TYPE,
              5: ARTWORK_TYPE,
              6: PATENT_TYPE,
            };

            return options[research_achievement_type] || [];
          },
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const excludeTypes = ['1', '2', '4', '5', '6']; // "项目、专利或软件著作权、奖励、文艺作品、著作"
            return !excludeTypes.includes(type);
          },
        },
        {
          label: '是否是代表性成果或项目',
          name: 'representative_or_project',
          key: 'representative_or_project',
          inputType: InputType.radio,
          renderOption: YES_NO,
        },
        {
          label: '名称',
          name: 'name',
          key: 'name',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const excludeTypes = ['1', '2', '3', '4', '5', '6', '7', '8', '10']; // "除了国家标准或行业标准"
            return !excludeTypes.includes(type);
          },
        },
        {
          label: '学科领域',
          name: 'disciplinary_field',
          key: 'disciplinary_field',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['1', '2', '3', '6']; // "项目", "著作", "专利或软件著作权"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '本人角色',
          name: 'role',
          key: 'role',
          inputType: InputType.select,
          renderOption: (form: FormPanelObject) => {
            const research_achievement_type = form.getFieldValue('research_achievement_type');
            const options = {
              1: PROJECT_ROLE,
              2: RESEARCH_ROLE,
              3: PAPER_ROLE,
              5: ARTWORK_ROLE,
              6: PATENT_ROLE,
              10: COMPETITION_ROLE,
            };

            return options[research_achievement_type] || [];
          },
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const excludeTypes = ['1', '2', '3', '5', '6', '7', '8', '9', '10']; // "除了奖励"
            return !excludeTypes.includes(type);
          },
        },
        {
          label: '日期',
          name: 'publication_date',
          key: 'publication_date',
          inputType: InputType.date,
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const excludeTypes = ['2', '3', '4', '5', '7', '8', '9', '10']; // "除了项目"
            return !excludeTypes.includes(type);
          },
        },
        {
          label: '批准日期',
          name: 'publication_date',
          key: 'publication_date',
          inputType: InputType.date,
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const excludeTypes = ['6'];
            return !excludeTypes.includes(type);
          },
        },
        {
          label: '报告题目',
          name: 'report_name',
          key: 'report_name',
          textRange: [0, 50],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const excludeTypes = ['6'];
            return !excludeTypes.includes(type);
          },
        },
        {
          label: '报告时间',
          name: 'report_date',
          key: 'report_date',
          inputType: InputType.date,
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const excludeTypes = ['6'];
            return !excludeTypes.includes(type);
          },
        },
        {
          label: '批准号',
          name: 'approval_number',
          key: 'approval_number',
          required: false,
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['1']; // 仅"项目"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '经费额度',
          name: 'funding_amount',
          key: 'funding_amount',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['1']; // 仅"项目"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '开始年月',
          name: 'start_year_month',
          key: 'start_year_month',
          inputType: InputType.date,
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['1']; // 仅"项目"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '结束年月',
          name: 'end_date',
          key: 'end_date',
          inputType: InputType.date,
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['1']; // 仅"项目"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '本人排名',
          name: 'ranking',
          key: 'ranking',
          textRange: [0, 10],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const excludeTypes = ['1']; // "论文", "国家标准或行业标准"
            return !excludeTypes.includes(type);
          },
        },
        {
          label: '本人排名',
          name: 'ranking',
          key: 'ranking',
          inputType: InputType.select,
          renderOption: PERSONAL_RANK,
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const excludeTypes = ['4']; // "论文", "国家标准或行业标准"
            return !excludeTypes.includes(type);
          },
        },
        {
          label: '委托单位',
          name: 'entrusting_unit',
          key: 'entrusting_unit',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['1']; // "项目", "咨询报告或研究报告"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '来源',
          name: 'source',
          key: 'source',
          inputType: InputType.select,
          renderOption: PROJECT_SOURCE,
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['1']; // 仅"项目"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '出版社名称',
          name: 'publisher_name',
          key: 'publisher_name',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['2']; // 仅包含在"著作"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '出版号',
          name: 'publication_number',
          key: 'publication_number',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['2']; // 仅包含在"著作"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '总字数',
          name: 'total_words',
          key: 'total_words',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['2']; // 仅包含在"著作"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '本人撰写字数',
          name: 'self_written_words',
          key: 'self_written_words',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['2']; // 仅包含在"著作"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '发表刊物名称',
          name: 'journal_name',
          key: 'journal_name',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['3']; // 仅"论文"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '卷号',
          name: 'volume_number',
          key: 'volume_number',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['3']; // 仅"论文"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '期号',
          name: 'issue_number',
          key: 'issue_number',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['3']; // 仅"论文"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '论文收录情况',
          name: 'indexing_status',
          key: 'indexing_status',
          inputType: InputType.children,
          children: <Cascader />,
          renderOption: (form: FormPanelObject) => {
            const research_achievement_type = form.getFieldValue('research_achievement_type');
            const options = {
              3: INDEXING_STATUS,
            };

            return options[research_achievement_type] || [];
          },
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['3']; // 仅"论文"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '起始页码',
          name: 'start_page',
          key: 'start_page',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['3']; // 仅"论文"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '结束页码',
          name: 'end_page',
          key: 'end_page',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['3']; // 仅"论文"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '等级',
          name: 'research_level',
          key: 'research_level',
          inputType: InputType.select,
          renderOption: RESEARCH_LEVEL,
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const excludeTypes = ['4']; // 奖励、指导学生...
            return !excludeTypes.includes(type);
          },
        },
        {
          label: '等级',
          name: 'research_level',
          key: 'research_level',
          textRange: [0, 50],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const excludeTypes = ['10']; // 奖励、指导学生...
            return !excludeTypes.includes(type);
          },
        },
        {
          label: '其他等级',
          name: 'other_level',
          key: 'other_level',
          textRange: [0, 10],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['4']; // 仅"奖勤"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '授权国家（地区）',
          name: 'authorized_country',
          key: 'authorized_country',
          inputType: InputType.select,
          renderOption: countries,
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['4']; // "奖勤"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '授权单位',
          name: 'authorized_organization',
          key: 'authorized_organization',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['4']; // "专利或软件著作权"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '完成地点',
          name: 'completion_location',
          key: 'completion_location',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['5']; // "文艺作品"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '专利号（登记号）',
          name: 'patent_number',
          key: 'patent_number',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['6']; // 仅"专利或软件著作权"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '委托方',
          name: 'entrusting_party',
          key: 'entrusting_party',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['entrusting_party', '7']; // 仅"国家标准或行业标准"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '证书（批件）号',
          name: 'certificate_number',
          key: 'certificate_number',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['8']; // 仅包含在"国家医药证书"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '颁布或批准时间',
          name: 'validity_period',
          key: 'validity_period',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['8']; // 仅"国家医药证书"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '发布日期',
          name: 'publish_date',
          key: 'publish_date',
          inputType: InputType.date,
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['8']; // 仅"国家医药证书"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '标准号',
          name: 'standard_number',
          key: 'standard_number',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['8', '9']; // 仅"国家标准或行业标准"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '发布单位',
          name: 'publishing_organization',
          key: 'publishing_organization',
          textRange: [0, 20],
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['8', '9']; // 仅"国家标准或行业标准"
            return !includeTypes.includes(type);
          },
        },
        {
          label: '本人承担工作描述',
          name: 'work_description',
          key: 'work_description',
          inputType: InputType.textarea,
          span: 24,
          textRange: [0, 200],
          props: {
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
          },
          hidden: (form: FormPanelObject) => {
            const type = form.getFieldValue('research_achievement_type');
            const includeTypes = ['5', '10']; // "文艺作品", "指导学生参加竞赛奖励"
            return !includeTypes.includes(type);
          },
        },
      ],
    },
  ];

  const { id: teacher_id } = useParams();

  const [formValue, setFormValue] = React.useState({ research_achievement_type: '1' });
  const [dataSource, setDataSource] = React.useState([]);
  const [currentRowId, setCurrentRowId] = React.useState(null);

  React.useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const res = await TeaResearchAchievementsSrv.list({ teacher_id });
    console.log('🚀 ~ fetchData ~ res:', res);
    if (res.success) {
      setDataSource(res.data);
    }
  };
  // 新增 | 编辑
  const [showFormModel, setFormModel] = React.useState(false);
  const [isEdit, setIsEdit] = React.useState(false);

  const handleAdd = () => {
    setIsEdit(false);
    setFormValue({ research_achievement_type: achievement_type });
    setFormModel(true);
  };

  const handleEdit = async (record: any) => {
    const { data } = await TeaResearchAchievementsSrv.detail(record.research_achievements_id);

    const params = {
      ...data,
    };
    setCurrentRowId(record.research_achievements_id);

    setFormValue(params);
    setIsEdit(true);
    setFormModel(true);
  };

  const handleDelete = (record: any) => {
    // content 按最字段内容为准，格式是否删除${证件类型}:${证件号码},姓名${姓名}的教师信息?
    const text = _.find(RESEARCH_TYPE, { value: String(record.research_achievement_type) })?.label || '';
    Modal.confirm({
      title: '删除',
      content: `是否删除考核年度: ${text} 相关信息?`,
      onOk: async () => {
        console.log('OK');
        const res = await TeaResearchAchievementsSrv.delete(record.research_achievements_id);
        if (res.success) {
          message.success('删除成功');
          fetchData();
        }
      },
    });
  };

  const handleSave = async (formPanelObject: FormPanelObject) => {
    const values = formPanelObject.getFieldsValue();
    console.log('🚀 ~ handleSave ~ values:', values);
    const params = {
      ...values,
      teacher_id,
    };

    if (params.publication_date) {
      params.publication_date = utils.formatTime(params.publication_date);
    }
    if (params.start_year_month) {
      params.start_year_month = utils.formatTime(params.start_year_month);
    }
    if (params.end_date) {
      params.end_date = utils.formatTime(params.end_date);
    }

    if (isEdit) {
      params.research_achievements_id = currentRowId;
    }

    // 新增 | 编辑
    const server = isEdit ? 'update' : 'add';
    const res = await TeaResearchAchievementsSrv[server](params);
    if (res.success) {
      message.success('保存成功');
      formPanelObject.resetFields();
      setFormModel(false);
      fetchData();
      setCurrentRowId(null);
    } else {
      formPanelObject.reVaildation(res);
    }
  };

  return (
    <Card title="教学科研成果及获奖信息" bordered={false}>
      {isEditPanel && (
        <Button type="primary" style={{ marginBottom: '20px' }} onClick={handleAdd}>
          新增
        </Button>
      )}
      <Table dataSource={dataSource} columns={columns} scroll={{ x: 'max-content' }} />
      <FormPanelWrapper
        title={
          isEdit
            ? isEditPanel
              ? '教学科研成果及获奖信息编辑'
              : '教学科研成果及获奖信息详情'
            : '教学科研成果及获奖信息新增'
        }
        visible={showFormModel}
        formValue={formValue}
        changeValue={setFormValue}
        formList={list}
        onCancel={() => setFormModel(false)}
        onSave={handleSave}
        isEdit={isEditPanel}
        isReset={false}
      />
    </Card>
  );
};

Groups.defaultProps = {
  isEditPanel: true,
};

export default Groups;
